package cn.zxw.utils;

import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Screen;
import javafx.stage.Stage;

import java.io.*;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * 功能描述:基于JavaFx原生实现的弹框--暂未使用 <br>
 * @Author: zxw
 * @Date: 2020/7/1 10:38
 */
public class CommenUtils {

    public static void showTimedDialog(String type,String title,String userOrOffice) {
        Rectangle2D bounds = Screen.getPrimary().getVisualBounds();
        Stage popup = new Stage();
        popup.setMinWidth(400);
        popup.setMinHeight(130);
        popup.setAlwaysOnTop(true);
        popup.initModality(Modality.APPLICATION_MODAL);
        popup.setX(bounds.getMaxX() - 400);
        popup.setY(bounds.getMaxY() - 190);
        Button closeBtn = new Button("立即前往");
        closeBtn.setOnAction(e -> {
            popup.close();
        });
        VBox root = new VBox();
        root.setPadding(new Insets(20));
        root.setAlignment(Pos.BASELINE_CENTER);
        root.setSpacing(20);
        root.getChildren().addAll(new Label(title),new Label(userOrOffice), closeBtn);
        Scene scene = new Scene(root);
        popup.setScene(scene);
        popup.setTitle(type);
        popup.show();

        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(4000);
                if (popup.isShowing()) {
                    Platform.runLater(() -> popup.close());
                }
            } catch (Exception exp) {
                exp.printStackTrace();
            }
        });
        thread.setDaemon(true);
        thread.start();
    }

    /**
     * 功能描述: 打开浏览器<br>
     * @Param: [url]
     * @Author: zxw
     * @Date: 2020/7/3 9:50
     */
    public static void browse(String id,String url,String token) throws Exception {
        // 获取操作系统的名字
        String osName = System.getProperty("os.name", "");
        if (osName.startsWith("Mac OS")) {
            // 苹果的打开方式
            Class fileMgr = Class.forName("com.apple.eio.FileManager");
            Method openURL = fileMgr.getDeclaredMethod("openURL",
                    new Class[] { String.class });
            openURL.invoke(null, new Object[] { url+"?noticId="+id+"&token="+token});
        } else if (osName.startsWith("Windows")) {
            // windows的打开方式。
            Runtime.getRuntime().exec(
                    "rundll32 url.dll,FileProtocolHandler " + url+"?noticId="+id+"&token="+token);
            // URLConnection conn = new URL("http://www.baidu.com").openConnection();
        } else {
            // Unix or Linux的打开方式
            String[] browsers = { "firefox", "opera", "konqueror", "epiphany",
                    "mozilla", "netscape" };
            String browser = null;
            for (int count = 0; count < browsers.length && browser == null; count++)
                // 执行代码，在brower有值后跳出，
                // 这里是如果进程创建成功了，==0是表示正常结束。
                if (Runtime.getRuntime()
                        .exec(new String[] { "which", browsers[count] })
                        .waitFor() == 0)
                    browser = browsers[count];
            if (browser == null)
                throw new Exception("Could not find web browser");
            else
                // 这个值在上面已经成功的得到了一个进程。
                Runtime.getRuntime().exec(new String[] { browser, url+"?noticId="+id+"&token="+token });
        }
    }

    /**
     * 功能描述: 获取配置文件属性值<br>
     * @Return: java.lang.String
     * @Author: zxw
     * @Date: 2020/7/4 17:16
     */
    public  static String splitTitle(Boolean flag,String value){
        StringBuilder stringBuilder = new StringBuilder();
        if(flag){//表示列表
            if(value.length()>=13){
                value = value.substring(0, 13);
            }else{
                return value;
            }
        }else {
            if(value.length()>=30){
                value = value.substring(0, 30);
            }
       }
        stringBuilder.append(value);
        stringBuilder.append("...");
        return stringBuilder.toString();
    }


    /**
     *
     * @param name
     * @return
     * @description 获取相对于resources目录下的路径
     */
    public static String getFilePathInResources(String name) {
        String resources = "resources";
        int resIdx = name.indexOf(resources);
        if (resIdx == -1) {
            return name;
        }
        return name.substring(resIdx + resources.length() + 1);
    }

    /**
     * @param name 文件名
     * @return
     * @version 1.2
     */
    public static String getFileBaseName(String name) {
        String result = "";
        String[] tempStrs = name.split("/");
        if (1 == tempStrs.length) { //只有文件名，即name: languageDemo.fxml
            result = StringUtil.trimExtension(name);
        } else {
            result = StringUtil.trimExtension(tempStrs[tempStrs.length - 1]);
        }
        return result;
    }

    /**
     * 功能描述:删除文件 <br>
     * @Param: [fileName]
     * @Return: boolean
     * @Author: zxw
     * @Date: 2020/7/4 20:41
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                System.out.println("删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            System.out.println("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }


    public static void writeFile(String fileName, Properties prop) {
        try {
            FileOutputStream oFile = new FileOutputStream(fileName, false);
            prop.store(oFile, null);
            oFile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取Properties对象
     * @return
     */
    public static Properties getProperties(String fileName){
        Properties properties = null;
        InputStream inputStream = null;
        try {
            if (new File(fileName).exists()) {
                properties = new Properties();
                InputStream in = new BufferedInputStream(new FileInputStream(fileName));
                properties.load(in);
            }
        } catch (FileNotFoundException e) {
            System.out.println(fileName+"文件未找到!");
        } catch (IOException e) {
            System.out.println("出现IOException");
        } finally {
            try {
                if (null != inputStream){
                    inputStream.close();
                }
            } catch (IOException e) {
                System.out.println(fileName+"文件流关闭出现异常");
            }
        }
        return properties;
    }


    // 写入快捷方式 是否自启动，快捷方式的名称，注意后缀是lnk
    public  boolean setAutoStart(boolean yesAutoStart, String lnk) {
        File f = new File(lnk);
        String p = f.getAbsolutePath();
        String startFolder = "";
        String osName = System.getProperty("os.name");
        String str = System.getProperty("user.home");
        if (osName.equals("Windows 7") || osName.equals("Windows 8") || osName.equals("Windows 10")
                || osName.equals("Windows Server 2012 R2") || osName.equals("Windows Server 2014 R2")
                || osName.equals("Windows Server 2016")) {
            startFolder = System.getProperty("user.home")
                    + "\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";
        }
        if (osName.endsWith("Windows XP")) {
            startFolder = System.getProperty("user.home") + "\\「开始」菜单\\程序\\启动";
        }
        if (setRunBySys(yesAutoStart, p, startFolder, lnk)) {
            return true;
        }
        return false;
    }

    // 设置是否随系统启动
    public boolean setRunBySys(boolean b, String path, String path2, String lnk) {
        File file = new File(path2 + "\\" + lnk);
        Runtime run = Runtime.getRuntime();
        File f = new File(lnk);

        // 复制
        try {
            if (b) {
                // 写入
                // 判断是否隐藏，注意用系统copy布置为何隐藏文件不生效
                if (f.isHidden()) {
                    // 取消隐藏
                    try {
                        Runtime.getRuntime().exec("attrib -H \"" + path + "\"");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (!file.exists()) {
                    run.exec("cmd /c copy " + formatPath(path) + " " + formatPath(path2));
                }
                // 延迟0.5秒防止复制需要时间
                Thread.sleep(500);
            } else {
                // 删除
                if (file.exists()) {
                    if (file.isHidden()) {
                        // 取消隐藏
                        try {
                            Runtime.getRuntime().exec("attrib -H \"" + file.getAbsolutePath() + "\"");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Thread.sleep(500);
                    }
                    run.exec("cmd /c del " + formatPath(file.getAbsolutePath()));
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 解决路径中空格问题
    private String formatPath(String path) {
        if (path == null) {
            return "";
        }
        return path.replaceAll(" ", "\" \"");
    }


}
